import React, { memo, useEffect, useState } from "react";
import { ExclamationCircleOutlined, EyeInvisibleOutlined, EyeTwoTone } from "@ant-design/icons";
import { Button, Form, Input, Modal, Table, Space, message, Select, Mentions } from "antd";
import { ResultEnum } from "@/enums/httpEnum";
// import { processMenus } from "@/utils/util";
import "./index.less";
import { searchAdminUserList, createAdminUser, updateAdminUser, deleteAdminUser } from "@/api/modules/adminUser";
import { IListQueryParams, IUser, ICreateUserInfo } from "@/api/interface/adminUser";
import TextArea from "antd/lib/input/TextArea";
import { IRole } from "@/api/interface/role";
import { getAllRoleList } from "@/api/modules/role";
import { encrypt } from "@/utils/crypto";
import useAuthPermission from "@/hooks/useAuthPermission";

// eslint-disable-next-line react/display-name
const AdminUserManage = memo(() => {
	// 按钮权限
	const [adminUserList, setAdminUserList] = useState<IUser[] | undefined>([]);
	const [toatl, setTotal] = useState(0);
	const [roleList, setRoleList] = useState<IRole[]>([]);
	// 新建框
	const [isModalOpen, setIsModalOpen] = useState(false);
	const [form] = Form.useForm<ICreateUserInfo>();
	const [submitting, setSubmitting] = useState(false);
	const [editId, setEditId] = useState<string | undefined | null>(null);
	const [queryParams, setQueruParams] = useState<IListQueryParams>({
		keyword: "",
		type: null,
		status: null,
		pageNum: 1,
		pageSize: 10
	});

	const onFinish = () => {
		form.resetFields();
	};
	const createModal = () => {
		getRoleList();
		form.resetFields();
		setIsModalOpen(true);
	};

	const handleOk = () => {
		setIsModalOpen(false);
	};

	const handleCancel = () => {
		setEditId(null);
		setIsModalOpen(false);
	};

	const editorForm = (formData: ICreateUserInfo) => {
		form.setFieldsValue(formData);
		setEditId(formData.userId);
		console.log(formData);
		setIsModalOpen(true);
	};

	const handleSubmit = async () => {
		try {
			await form.validateFields();
			setSubmitting(true);
			const values = await form.getFieldsValue();
			let submitFn: Function = createAdminUser;
			console.log(values);
			const params = {
				...values,
				password: values.password ? encrypt(values.password) : null
			};
			console.log(editId);
			if (editId) {
				params.userId = editId;
				submitFn = updateAdminUser;
			}

			const { code, msg } = await submitFn(params);
			if (code === 200) {
				await getAdminUserList();
				setEditId(null);
				message.success(msg);
				handleCancel();
				form.resetFields();
			}

			setSubmitting(false);
		} catch (err) {
			setSubmitting(false);
			console.log(err);
		}
	};

	// 获取数据
	const getAdminUserList = async () => {
		const { code, data } = await searchAdminUserList(queryParams);
		if (code === ResultEnum.SUCCESS) {
			setAdminUserList(data?.list);
			setTotal(data?.total || 0);
		}
		// setAdminUserList(res);
	};

	const getRoleList = async () => {
		const { code, data } = await getAllRoleList();
		if (code === ResultEnum.SUCCESS) {
			setRoleList(data || []);
		}
	};

	useEffect(() => {
		getAdminUserList();
	}, []);

	useEffect(() => {
		getAdminUserList();
	}, [queryParams]);

	const { confirm } = Modal;
	const showConfirm = (userId: string) => {
		confirm({
			title: "提示",
			icon: <ExclamationCircleOutlined />,
			content: "确定删除当前用户？",
			async onOk() {
				const { code, msg } = await deleteAdminUser(userId);
				if (code === 200) {
					message.success(msg);
					await getAdminUserList();
				}
			},
			onCancel() {
				console.log("Cancel");
			}
		});
	};

	const columns: any[] = [
		{
			title: "用户账号",
			dataIndex: "username",
			key: "username",
			align: "center"
		},
		{
			title: "用户昵称",
			dataIndex: "nickname",
			key: "nickname",
			align: "center"
		},
		{
			title: "用户角色",
			dataIndex: "roleName",
			key: "roleName",
			align: "center"
		},
		{
			title: "用户头像",
			dataIndex: "avatar",
			key: "avatar",
			align: "center",
			render: (avatar: string) => {
				return <img width="50px" height="50px" src={avatar} alt="" />;
			}
		},
		{
			title: "电话",
			dataIndex: "phone",
			key: "phone",
			align: "center"
		},
		{
			title: "邮箱",
			dataIndex: "email",
			key: "email",
			align: "center"
		},
		{
			title: "最近登录时间",
			dataIndex: "recentLoginTime",
			key: "recentLoginTime",
			align: "center"
		},
		{
			title: "创建时间",
			dataIndex: "createTime",
			key: "createTime",
			align: "center"
		},
		{
			title: "创建时间",
			dataIndex: "createTime",
			key: "createTime",
			align: "center"
		},
		{
			title: "操作",
			dataIndex: "userId",
			key: "userId",
			render: (userId: string, record: ICreateUserInfo) => {
				return (
					<Space>
						{useAuthPermission("adminUser:update") && <a onClick={() => editorForm(record)}>编辑</a>}
						{useAuthPermission("adminUser:delete") && <a onClick={() => showConfirm(userId)}>删除</a>}
					</Space>
				);
			},
			align: "center"
		}
	];

	return (
		<div className="card admin-user-manage-box">
			<div className="create">
				{useAuthPermission("adminUser:add") && (
					<Button type="primary" onClick={createModal}>
						添加管理员
					</Button>
				)}
			</div>
			<Table
				bordered={true}
				dataSource={adminUserList?.map(item => {
					return {
						...item,
						key: item.userId
					};
				})}
				columns={columns}
				rowKey={record => record.userId}
				pagination={{
					total: toatl,
					onChange(page, pageSize) {
						setQueruParams({
							...queryParams,
							pageNum: page,
							pageSize: pageSize
						});
					}
				}}
			/>
			<Modal
				title="新建用户"
				open={isModalOpen}
				onOk={handleOk}
				onCancel={handleCancel}
				width={600}
				footer={[
					<Button key="back" onClick={handleCancel}>
						取消
					</Button>,
					<Button key="submit" type="primary" loading={submitting} onClick={handleSubmit}>
						确定
					</Button>
				]}
			>
				<Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 16 }} layout="horizontal" onFinish={onFinish}>
					<Form.Item label="用户账号" name="username" rules={[{ required: true }]}>
						<Input placeholder="请输入用户账号" />
					</Form.Item>
					<Form.Item label="用户名称" name="nickname" rules={[{ required: true }]}>
						<Input placeholder="请输入用户名称" />
					</Form.Item>
					<Form.Item label="密码" name="password" rules={[{ required: editId ? false : true }]}>
						<Input.Password
							placeholder="请输入密码"
							type="password"
							iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
						/>
					</Form.Item>
					<Form.Item label="用户角色" name="roleId" rules={[{ required: true }]}>
						<Select
							placeholder="请选择角色"
							style={{ width: 120 }}
							options={roleList.map(item => {
								return {
									label: item.name,
									value: item.id
								};
							})}
						/>
					</Form.Item>
					<Form.Item label="用户说明" name="notes">
						<TextArea showCount maxLength={100} style={{ height: 120 }} placeholder="请输入用户说明" />
					</Form.Item>
					<Form.Item
						label="邮箱"
						name="email"
						rules={[
							{ required: false },
							{
								pattern: new RegExp(
									/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
									"g"
								),
								message: "请输入正确的邮箱号"
							}
						]}
					>
						<Mentions
							rows={1}
							placeholder="请输入用户邮箱"
							options={[
								{
									value: "163.com",
									label: "163.com"
								},
								{
									value: "qq.com",
									label: "qq.com"
								},
								{
									value: "google.com",
									label: "google.com"
								}
							]}
						/>
					</Form.Item>
					<Form.Item
						label="用户手机"
						name="phone"
						rules={[
							{ required: false },
							{ pattern: new RegExp(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/, "g"), message: "请输入正确的手机号" }
						]}
					>
						<Input maxLength={11} placeholder="请输入用户手机" />
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
});
export default AdminUserManage;
